﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SystemCenterSoa.BaseLibrary.Tools.HelperTools;
using SystemCenterSoa.BaseLibrary.Tools.IosTools;
using SystemCenterSoa.BaseLibrary.Tools.TextTools;
using SystemCenterSoa.BaseLibrary.Tools.TypeTools;
using SystemCenterSoa.DtoModel.Common;
using SystemCenterSoa.DtoModel.SystemManager;
using SystemCenterSoa.IRepository.SystemManager;
using SystemCenterSoa.PoModel.SystemManager;

namespace SystemCenterSoa.Service.SystemManager
{
    public class AdminUserService
    {
        private IAdminUserRepository _adminUserRepository;

        private RoleService _roleService;

        private ModuleService _moduleService;
        public AdminUserService(IAdminUserRepository adminUserRepository, RoleService roleService, ModuleService moduleService)
        {
            _adminUserRepository = adminUserRepository;
            _roleService = roleService;
            _moduleService = moduleService;
        }

        public PagerResult<AdminUserPo> SearchPage(SearchModel searchModel)
        {
            return _adminUserRepository.SearchPage(searchModel);
        }
        public bool AdminUserAdd(AdminUserDto view)
        {
            view.pass_word = StringMd5.Md5Hash32Salt(view.pass_word);
            return _adminUserRepository.AdminUserAdd(view);
        }

        public AdminUserPo GetAdminUserByUserName(string userName)
        {
            return _adminUserRepository.GetAdminUserByUserName(userName);
        }
        public bool VAdmminUserName(string userName)
        {
            if (GetAdminUserByUserName(userName) == null) return true;
            return false;
        }

        public bool AdminUserUpdate(AdminUserDto view)
        {
            return _adminUserRepository.AdminUserUpdate(view);
        }

        public AdminUserDto GetAdminUserViewByUserName(string userName)
        {
            return _adminUserRepository.GetAdminUserViewByUserName(userName);
        }
        public bool AdminUserPwdUpdate(string pwd, string userName)
        {
            pwd=StringMd5.Md5Hash32Salt(pwd);
            return _adminUserRepository.AdminUserPwdUpdate(pwd, userName);
        }


        /// <summary>
        /// 登录用户初始化
        /// </summary>
        /// <param name="AdminUserDto"></param>
        /// <returns></returns>
        public LoginUserDto LoginBuild(AdminUserDto AdminUserDto)
        {
            LoginJwtObjDto ljo = new LoginJwtObjDto()
            {
                UserName = AdminUserDto.user_name,
                LoginDate = DateTime.Now
            };
            string token = JwtUtil.Encode(ljo);
            LoginUserDto LoginUserDto = new LoginUserDto();
            LoginUserDto.Token = token;
            ModelCopier.CopyModel(AdminUserDto, LoginUserDto);
            //初始化登录用户下面的所有角色
            LoginUserDto.Roles = _roleService.GetRoleDbsByUserName(LoginUserDto.user_name);

            //初始化登录用户下面的所有权限
            LoginUserDto.ModelCodes = _moduleService.GetModulePosByUserName(LoginUserDto.user_name).
                Select(c => c.module_code).ToList();


            LoginBulidSetRedis(LoginUserDto);


            return LoginUserDto;

        }
        public void LoginBulidSetRedis(LoginUserDto LoginUserDto)
        {
            MyRedisHelper.Set(LoginUserDto.user_name, LoginUserDto, 12000);
        }

        public LoginUserDto Login(string userName, string passWord,out string mess)
        {
            if (string.IsNullOrWhiteSpace(userName))
            {
                mess = "参数错误";
                return null;
            }
            if (string.IsNullOrWhiteSpace(passWord))
            {
                mess = "参数错误";
                return null;
            }
            AdminUserDto AdminUserDto = _adminUserRepository.GetAdminUserViewByUserName(userName);
            if (AdminUserDto == null)
            {
                mess = "用户名不正确";
                return null;
            }
            passWord = StringMd5.Md5Hash32Salt(passWord);
            if (AdminUserDto.pass_word != passWord)
            {
                mess = "密码错误";
                return null;
            }

            mess = "登录成功";
            return LoginBuild(AdminUserDto);



        }


        public bool VToken(string token)
        { 
            if(string.IsNullOrWhiteSpace(token) ) return false;
            LoginUserDto user = GetLoginUserInRedisByToken(token);
            if (user != null)
            {
                LoginBulidSetRedis(user); //刷新过期时间
                return true;
            }
            return false;


        }

        public LoginUserDto GetLoginUserInRedisByToken(string token)
        {
            if (string.IsNullOrWhiteSpace(token)) return null;
            LoginJwtObjDto LoginJwtObjDto = JwtUtil.Decode<LoginJwtObjDto>(token);
            if (LoginJwtObjDto == null) return null;
            LoginUserDto user = MyRedisHelper.Get<LoginUserDto>(LoginJwtObjDto.UserName);
            return user;
        }

        public static string GetTokenInHeader()
        {
            var IHttpContextAccessor = DiTools.GetDiObj<IHttpContextAccessor>();
           
            Microsoft.Extensions.Primitives.StringValues token;
            if (IHttpContextAccessor.HttpContext.Request.Headers.TryGetValue("X-Token", out token)) //获取token
            {
                return token;
            }
            return null;
        }
        public static LoginUserDto GetLoginUser()
        {
            string token = GetTokenInHeader();
            if (string.IsNullOrWhiteSpace(token)) return null;
            AdminUserService bll = DiTools.GetDiObjScoped<AdminUserService>();
            return bll.GetLoginUserInRedisByToken(token);
           // AdminUserService bll = new AdminUserService(DiTools.GetDiObjScoped<IAdminUserDal>(),
           //     DiTools.GetDiObjScoped<RoleDbBll>(),
           //      DiTools.GetDiObjScoped<ModuleDbBll>()
           //     );
           //return bll.GetLoginUserInRedisByToken(token);
        }

        public  static bool LoginOut()
        {
            try
            {
                var LoginUserDto = GetLoginUser();
                if (LoginUserDto != null) return MyRedisHelper.Remove(LoginUserDto.user_name);  //删除redis的登录用户数据
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
           


        }
        
    }
}
